# _*_ encoding:utf-8 _*_

from random import Random
from django.core.mail import send_mail

from .models import EmailVarifyRecord
from MxOnline.settings import EMAIL_FROM


def random_str(random_length=8):
    str = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(random_length):
        str += chars[random.randint(0, length)]
    return str


def send_register_email(email, send_type='register'):
    email_record = EmailVarifyRecord()
    code = random_str(16)
    email_record.code = code
    email_record.email = email
    email_record.send_type = send_type
    email_record.save()

    email_title = ''
    email_body = ''

    error_msg = u'success'
    if send_type == 'register':
        email_title = u'湖南省第一测绘院注册激活链接'
        email_body = u'请点击下面的链接激活你的账号: http://localhost:8080/active/{}/'.format(
            code)
    elif send_type == 'reset':
        email_title = u'湖南省第一测绘院重置密码链接'
        email_body = u'请点击下面的链接重置你的账号: http://localhost:8080/reset/{}/'.format(
            code)
    else:
        return '消息类型\'{}\'无效'.format(send_type)
    try:
        send_status = send_mail(
            email_title, email_body, EMAIL_FROM, [email])
        if send_status == 1:
            return u'success'
    except Exception as e:
        error_msg = str(e)

    return error_msg
